package com.keyou.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keyou.reggie.common.CustomException;
import com.keyou.reggie.dto.SetmealDTO;
import com.keyou.reggie.entity.SetMeal;
import com.keyou.reggie.entity.SetmealDish;
import com.keyou.reggie.mapper.SetMealMapper;
import com.keyou.reggie.service.SetMealService;
import com.keyou.reggie.service.SetmealDishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: klq
 * @Date: 2023/1/10 16:47
 * @Description:
 */
@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, SetMeal> implements SetMealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public void saveWithDish(SetmealDTO setmealDTO) {
        //保存套餐信息
        this.save(setmealDTO);
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        List<SetmealDish> list = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDTO.getId());
            return item;
        }).collect(Collectors.toList());
        //保存套餐关联的菜品信息
        setmealDishService.saveBatch(list);
    }

    @Override
    @Transactional
    public void deleteWithDish(List<Long> ids) {
        //先判断一下能不能删，如果status为1，则套餐在售，不能删
        //select * from setmeal where id in (ids) and status = 1
        LambdaQueryWrapper<SetMeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.in(SetMeal::getId, ids);
        setmealLambdaQueryWrapper.eq(SetMeal::getStatus, 1);
        long count = this.count(setmealLambdaQueryWrapper);
        if (count > 0) {
            throw new CustomException("套餐正在售卖中，请先停售再进行删除");
        }
        //删除套餐数据
        this.removeBatchByIds(ids);
        //继续删除套餐关联的菜品数据
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(setmealDishLambdaQueryWrapper);
    }


}